package com.dps.omc.agent;

import com.dps.omc.agent.queue.consumer.ConsumeQueueContainer;
import com.dps.omc.agent.queue.consumer.tasker.factory.CommandRecTaskerFactory;
import com.dps.omc.agent.queue.consumer.tasker.factory.UpgradeRecTaskerFactory;
import com.dps.omc.agent.utils.Constants;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.wisdom.api.DefaultController;
import org.wisdom.api.annotations.Controller;

import java.io.FileInputStream;
import java.net.InetAddress;
import java.util.Properties;

/**
 * Created by lip on 2015-12-17.
 */

@Controller
public class QueueListenerController extends DefaultController {

    private ActiveMQConnectionFactory targetConnectionFactory = null;
    private ConsumeQueueContainer commandContainer = null;
    private ConsumeQueueContainer upgradeContainer = null;


    public QueueListenerController() throws Exception {

        init();
    }

    private void init() throws Exception
    {
        Properties pps = new Properties();
        pps.load(new FileInputStream("conf/queue.properties"));
        String url = pps.getProperty("queue.host");
        String user = pps.getProperty("queue.user");
        String password = pps.getProperty("queue.pass");

//        String user = ActiveMQConnection.DEFAULT_USER;
//        String password = ActiveMQConnection.DEFAULT_PASSWORD;
//        String url = "tcp://127.0.0.1:61616";

//        String commandSubject = Constants.COMMAND_SUBJECT;
        String ip =  InetAddress.getLocalHost().getHostAddress();
//        String commandSubject = InetAddress.getLocalHost().getHostAddress();
        String commandSubject = Constants.COMMAND_SUBJECT+"_"+ip;
        String upgradeSubject = Constants.UPGRADE_SUBJECT+"_"+ip;

        targetConnectionFactory = new ActiveMQConnectionFactory(user,password,url);
        //初始监听任务队列
        this.initCommandContainer(targetConnectionFactory,commandSubject);
        //初始监听更新队列
        this.initUpgradeContainer(targetConnectionFactory,upgradeSubject);
    }

    //初始监听任务队列
    private void initCommandContainer(ActiveMQConnectionFactory targetConnectionFactory,String commandSubject) throws Exception {
        commandContainer = new ConsumeQueueContainer(targetConnectionFactory,commandSubject,new CommandRecTaskerFactory());
        commandContainer.consumeMessage();
    }
    //初始监听更新队列
    private void initUpgradeContainer(ActiveMQConnectionFactory targetConnectionFactory,String upgradeSubject) throws Exception {
        upgradeContainer = new ConsumeQueueContainer(targetConnectionFactory,upgradeSubject,new UpgradeRecTaskerFactory());
        upgradeContainer.consumeMessage();
    }

}
